/////////////////////////////////////////////////////////////////////////////
// Name:        application.cpp
// Purpose:     
// Author:      Brant Young
// Modified by: 
// Created:     Fri 02 Mar 2007 20:09:29 CST
// RCS-ID:      
// Copyright:   (C) Victsoft 2007
// Licence:     GPL 2.0
/////////////////////////////////////////////////////////////////////////////
#include <wx/wx.h>
#include <wx/wxsqlite3.h>
#include <wx/wxhtml.h>

#include "dictquery.h"
#include "highlight.h"

DictQuery::DictQuery(const wxString& dbpath) {
	try {
		db.Open(dbpath);
		
		wxString sql(_T("SELECT name, author, email, website, \
				description, date, version FROM dictinfo;"));

		//wxMessageBox(_("wxSQLite3ResultSet"));
	    wxSQLite3ResultSet dicts_ret = db.ExecuteQuery(sql);
		//wxMessageBox(_("wxSQLite3ResultSet"));
		while (dicts_ret.NextRow()) {
			name = dicts_ret.GetString(0);
			//category = dicts_ret.GetString(1);
			author = dicts_ret.GetString(1);
			email = dicts_ret.GetString(2);
			website = dicts_ret.GetString(3);
			description = dicts_ret.GetString(4);
			date = dicts_ret.GetString(5);
			version = dicts_ret.GetString(6);
		}
		
	} catch (wxSQLite3Exception& e) {
		wxLogError(wxString::Format(_T("%s%n"),e.GetMessage().c_str(),e.GetErrorCode()));
		// log error
	}
}

DictQuery::~DictQuery() {
	db.Close();
}


bool DictQuery::query(const wxString& word, wxHtmlWindow* explain_wnd) {
	wxString s_word = word;
	s_word.Replace(_T("\'"), _T("\'\'"));
	
	try {
		wxString sql;
		sql.Printf(_T("SELECT explain FROM wordslist WHERE word=\'%s\'"),
				s_word.c_str()
				);
		
	    wxSQLite3ResultSet dicts_ret = db.ExecuteQuery(sql);
		while (dicts_ret.NextRow()) {
			wxString temp = dicts_ret.GetString(0);
			explain_wnd->SetPage(Formatter::get().format(name, word, temp));
			return true;
		}
	
		return false;
	} catch (wxSQLite3Exception& e) {
		wxMessageBox(wxString::Format(_T("%s%n"),e.GetMessage().c_str(),e.GetErrorCode()), wxT("Fatal error!"), wxOK|wxICON_ERROR);
		return false;
		// log error
	}
	return false;
}
